package org.smart4j.chapter4.threadLocal.example;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtil {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/web_shiyan";
    private static final String username = "root";
    private static final String password = "bobo1356";

    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<Connection>();

    public static Connection getConnection(){
        Connection conn = connectionThreadLocal.get();
        if (conn == null){
            try {
                Class.forName(driver);
                connectionThreadLocal.set(DriverManager.getConnection(url, username, password));
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        return connectionThreadLocal.get();
    }

    public static void closeConnection(){
        Connection conn = connectionThreadLocal.get();
        try {
            if (conn != null){
                conn.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            connectionThreadLocal.remove();
        }
    }
}
